package com.qianying.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qianying.comment.CommonResult;
import com.qianying.entity.SettlementMethod;
import com.qianying.mapper.SettlementMethodMapper;
import com.qianying.service.SettlementMethodService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.List;

/**
 * 结算方式服务实现类
 * 实现结算方式相关的业务逻辑
 */
@Service
public class SettlementMethodServiceImpl extends ServiceImpl<SettlementMethodMapper, SettlementMethod> implements SettlementMethodService {

    @Autowired
    private SettlementMethodMapper settlementMethodMapper;

    /**
     * 分页查询结算方式列表
     */
    @Override
    public CommonResult<IPage<SettlementMethod>> getPage(Page<SettlementMethod> page, SettlementMethod settlementMethod) {
        LambdaQueryWrapper<SettlementMethod> queryWrapper = new LambdaQueryWrapper<>();
        // 结算方式代码精确查询
        if (StringUtils.hasText(settlementMethod.getMethodCode())) {
            queryWrapper.eq(SettlementMethod::getMethodCode, settlementMethod.getMethodCode());
        }
        // 结算方式名称模糊查询
        if (StringUtils.hasText(settlementMethod.getMethodName())) {
            queryWrapper.like(SettlementMethod::getMethodName, settlementMethod.getMethodName());
        }
        // 账期天数精确查询
        if (settlementMethod.getPeriodDays() != null) {
            queryWrapper.eq(SettlementMethod::getPeriodDays, settlementMethod.getPeriodDays());
        }
        // 状态精确查询
        if (settlementMethod.getStatus() != null) {
            queryWrapper.eq(SettlementMethod::getStatus, settlementMethod.getStatus());
        }
        // 按ID升序排序
        queryWrapper.orderByAsc(SettlementMethod::getId);
        // 执行分页查询
        IPage<SettlementMethod> resultPage = settlementMethodMapper.selectPage(page, queryWrapper);
        // 填充状态名称
        resultPage.getRecords().forEach(method -> {
            method.setStatusName(method.getStatus() == 1 ? "已启用" : "已禁用");
        });
        return CommonResult.success(resultPage);
    }

    /**
     * 根据ID查询结算方式详情
     */
    @Override
    public CommonResult<SettlementMethod> getById(Long id) {
        // 空值校验
        if (id == null) {
            return CommonResult.failed("ID不能为空");
        }
        // 查询数据
        SettlementMethod method = settlementMethodMapper.selectById(id);
        if (method == null) {
            return CommonResult.failed("未找到ID为" + id + "的结算方式");
        }
        // 填充状态名称
        method.setStatusName(method.getStatus() == 1 ? "已启用" : "已禁用");
        return CommonResult.success(method);
    }

    /**
     * 新增结算方式
     */
    @Override
    public CommonResult<?> saveMethod(SettlementMethod settlementMethod) {
        // 空值校验
        if (settlementMethod == null) {
            return CommonResult.failed("提交的数据不能为空");
        }

        // 代码和名称不能为空
        if (!StringUtils.hasText(settlementMethod.getMethodCode())) {
            return CommonResult.failed("结算方式代码不能为空");
        }
        if (!StringUtils.hasText(settlementMethod.getMethodName())) {
            return CommonResult.failed("结算方式名称不能为空");
        }

        // 校验代码唯一性
        LambdaQueryWrapper<SettlementMethod> codeWrapper = new LambdaQueryWrapper<>();
        codeWrapper.eq(SettlementMethod::getMethodCode, settlementMethod.getMethodCode());
        if (settlementMethodMapper.selectCount(codeWrapper) > 0) {
            return CommonResult.failed("结算方式代码已存在");
        }

        // 校验名称唯一性
        LambdaQueryWrapper<SettlementMethod> nameWrapper = new LambdaQueryWrapper<>();
        nameWrapper.eq(SettlementMethod::getMethodName, settlementMethod.getMethodName());
        if (settlementMethodMapper.selectCount(nameWrapper) > 0) {
            return CommonResult.failed("结算方式名称已存在");
        }
        settlementMethod.setId(null);
        // 执行新增
        int rows = settlementMethodMapper.insert(settlementMethod);
        return rows > 0 ? CommonResult.success("新增结算方式成功") : CommonResult.failed("新增结算方式失败");
    }

    /**
     * 更新结算方式
     */
    @Override
    public CommonResult<?> updateMethod(SettlementMethod settlementMethod) {
        // 空值校验
        if (settlementMethod == null) {
            return CommonResult.failed("提交的数据不能为空");
        }
        // ID不能为空
        if (settlementMethod.getId() == null) {
            return CommonResult.failed("ID不能为空");
        }
        // 代码和名称不能为空
        if (!StringUtils.hasText(settlementMethod.getMethodCode())) {
            return CommonResult.failed("结算方式代码不能为空");
        }
        if (!StringUtils.hasText(settlementMethod.getMethodName())) {
            return CommonResult.failed("结算方式名称不能为空");
        }

        // 校验数据存在性
        SettlementMethod existing = settlementMethodMapper.selectById(settlementMethod.getId());
        if (existing == null) {
            return CommonResult.failed("未找到ID为" + settlementMethod.getId() + "的结算方式");
        }

        // 校验代码唯一性（排除当前ID）
        LambdaQueryWrapper<SettlementMethod> codeWrapper = new LambdaQueryWrapper<>();
        codeWrapper.eq(SettlementMethod::getMethodCode, settlementMethod.getMethodCode())
                .ne(SettlementMethod::getId, settlementMethod.getId());
        if (settlementMethodMapper.selectCount(codeWrapper) > 0) {
            return CommonResult.failed("结算方式代码已存在");
        }

        // 校验名称唯一性（排除当前ID）
        LambdaQueryWrapper<SettlementMethod> nameWrapper = new LambdaQueryWrapper<>();
        nameWrapper.eq(SettlementMethod::getMethodName, settlementMethod.getMethodName())
                .ne(SettlementMethod::getId, settlementMethod.getId());
        if (settlementMethodMapper.selectCount(nameWrapper) > 0) {
            return CommonResult.failed("结算方式名称已存在");
        }

        // 执行更新
        int rows = settlementMethodMapper.updateById(settlementMethod);
        return rows > 0 ? CommonResult.success("更新结算方式成功") : CommonResult.failed("更新结算方式失败");
    }

    /**
     * 更新结算方式启用状态
     */
    @Override
    public CommonResult<?> updateStatus(Long id, Integer status) {
        // 空值校验
        if (id == null) {
            return CommonResult.failed("ID不能为空");
        }
        if (status == null || (status != 0 && status != 1)) {
            return CommonResult.failed("状态值无效，必须为0或1");
        }

        // 校验数据存在性
        SettlementMethod existing = settlementMethodMapper.selectById(id);
        if (existing == null) {
            return CommonResult.failed("未找到ID为" + id + "的结算方式");
        }

        // 执行更新
        existing.setStatus(status);
        int rows = settlementMethodMapper.updateById(existing);
        return rows > 0 ? CommonResult.success("更新结算方式状态成功") : CommonResult.failed("更新结算方式状态失败");
    }

    /**
     * 根据ID删除结算方式
     */
    @Override
    public CommonResult<?> removeById(Long id) {
        // 空值校验
        if (id == null) {
            return CommonResult.failed("ID不能为空");
        }
        // 校验数据存在性
        SettlementMethod existing = settlementMethodMapper.selectById(id);
        if (existing == null) {
            return CommonResult.failed("未找到ID为" + id + "的结算方式");
        }
        // 执行删除
        int rows = settlementMethodMapper.deleteById(id);
        return rows > 0 ? CommonResult.success("删除结算方式成功") : CommonResult.failed("删除结算方式失败");
    }

    /**
     * 查询所有结算方式（不分页）
     */
    @Override
    public CommonResult<List<SettlementMethod>> getAll() {
        LambdaQueryWrapper<SettlementMethod> queryWrapper = new LambdaQueryWrapper<>();
        // 按ID升序排序
        queryWrapper.orderByAsc(SettlementMethod::getId);
        // 查询所有数据
        List<SettlementMethod> methodList = settlementMethodMapper.selectList(queryWrapper);
        // 填充状态名称
        methodList.forEach(method -> {
            method.setStatusName(method.getStatus() == 1 ? "已启用" : "已禁用");
        });
        return CommonResult.success(methodList);
    }
}